<template>
    <action-bar :actionBarData="actionBarData" @search="searchByNameOrTime" @addMsg="addBanner" @clearInput="clearInput"></action-bar>
    <div class="banner-list">
      <el-table ref="tableRef"  :data="tableData" style="width: 100%" max-height="250">
        <el-table-column v-if="isDeleteBatch" class="selection" fixed type="selection"/>
        <el-table-column class="index" fixed type="index" label="编号"/>
        <el-table-column prop="b_name" sortable label="名称" width="250" />
        <el-table-column prop="b_path" label="图片预览">
            <template #default="scope">
                <div class="img-preview" style="display: flex; align-items: center" v-if="scope.row.b_path">
                    <viewer>
                        <img :src="scope.row.b_path">
                    </viewer>
                </div>
                <div style="display: flex; align-items: center" v-else>
                    无图片
                </div>
            </template>
        </el-table-column>
        <el-table-column prop="b_time" sortable label="添加时间"/>
        <el-table-column prop="b_link" label="跳转链接"/>
        <el-table-column label="操作" class-name="handle-cell">
            <template #default="scope">
                <div class="b-l_handle">
                    <div class="state-btn-div">
                        <el-switch v-model="stateList[`${ scope.row.bid }`].state" :loading="stateList[`${ scope.row.bid }`].loading" 
                            @click="changeBannerState(scope.row.bid, stateList[`${ scope.row.bid }`])"/>
                        <span v-if="stateList[`${ scope.row.bid }`].state">启用</span>
                        <span v-else>停用中</span>
                    </div>
                    <button class="table-fix-btn t-change-btn" @click.prevent="updataRow(scope.row)">
                        <div></div>
                        更改
                    </button>
                    <button class="table-fix-btn t-delete-btn" @click.prevent="deleteRow(scope.$index, scope.row)">
                        删除
                    </button>
                </div>
            </template>
        </el-table-column>
        </el-table>
        <div class="table-footer">
            <div class="f-l-r">
                <el-checkbox v-model="isDeleteBatch" label="批量删除" style="margin-right: 1rem;" @change="isShowDeleteSelection"/>
                <el-button type="danger" class="delete-btn" @click.prevent="getDeleteData">批量删除</el-button>
                </div>
                <!-- 分页 -->
            <Pagination :list="bannerList" @getTableList="getTableList"></Pagination>
        </div>
    </div>
    <dialog-alert v-if="isdeleteAlert" :data="deleteAlertData" @on-confirm="onConfirm" @on-close="onConcel">
        <div>
            <h2>是否删除下列选中的轮播图？</h2>
            <el-table :data="deleteDate" style="width: 100%" max-height="250" class="delete-table">
                <el-table-column class="index" fixed type="index" label="编号"/>
                <el-table-column prop="b_name" label="名称" width="250" />
                <el-table-column prop="b_path" label="图片预览">
                    <template #default="scope">
                        <div class="img-preview" style="display: flex; align-items: center" v-if="scope.row.b_path">
                            <viewer>
                                <img :src="scope.row.b_path">
                            </viewer>
                        </div>
                        <div style="display: flex; align-items: center" v-else>
                            无图片
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </dialog-alert>
    <edit-banner-alert v-if="isShowEditBannerAlert" :type="type" ref="editBannerAlertRef" @onCloseEditBannerAlert="onCloseEditBannerAlert" @getBannerList="getBannerList"></edit-banner-alert>
</template>
  
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref, toRefs, watch, computed, nextTick } from 'vue'
import { IBannerInfoModel } from '../manage-banner.model'
import { format } from '@/utils/util'
import manageBannerStore from '../manage-banner.store'
import EditBannerAlert from './alert/edit-banner-alert.vue'

const manageBannerSe = manageBannerStore()

// 获取轮播图数据
let bannerList = ref([])
const getBannerList = () => {
    manageBannerSe.getBannerList().then((res: any) => {
        bannerList.value = res.results
        handleStateList()
    })
}

// 获取分页后要显示的数据
let tableData = ref([])
const getTableList = (value: any) => {
    tableData.value = value
    tableRef.value.setScrollTop(0)
}

// actionBar数据
const actionBarData = computed(() => {
    return {
        addButtonMsg: '添加轮播图',
        inputPlaceholder1: '按时间搜索',
        inputPlaceholder2: '按名称搜索',
    }
})

// 清空搜索栏
const clearInput = () => {
    getBannerList()
}

// 搜索
const searchByNameOrTime = (type: string, value: string) => {
    if(type == '1' && value) {
        value = format(value, '-')
    }
    const data = {
        searchType: type == '1' ? 'T' : 'N',
        searchText: value ? value : ''
    }
    manageBannerSe.getBannerByNameOrTime(data).then((res: any) => {
        if(res.status == 'success') {
            bannerList.value = res.results
        } else {
            ElMessage.error('搜索失败！')
        }
    })
}

// 添加轮播图的弹窗显示
let type = ref<string>('')
let isShowEditBannerAlert = ref<boolean>(false)
const addBanner = () => {
    isShowEditBannerAlert.value = true
    type.value = 'add'
    window.sessionStorage.setItem('uploadApi', '/api/banner/uploadBanner')
}

// 弹窗内点击取消时
const onCloseEditBannerAlert = () => {
    isShowEditBannerAlert.value = false
}

// 获取轮播图数据
let stateList = ref<any>({}) // 轮播图启用状态相关数据
const handleStateList = () => {
    let obj: any = bannerList.value
    let obj1: any = {}
    for (const item of obj) {
        item.b_time = item.b_time.split('T')[0]
        item.b_state = item.b_state == '1' ? true : false 
        obj1[`${ item.bid }`] = { 'state': item.b_state, 'loading': false }
    }
    stateList.value = obj1
}

// 点击更改按钮
let editBannerAlertRef = ref<any>(null)
const updataRow = (value: object) => {
    isShowEditBannerAlert.value = true
    type.value = 'change'
    window.sessionStorage.setItem('currentBannerId', value.bid)
    isShowEditBannerAlert.value = true
    window.sessionStorage.setItem('uploadApi', '/api/banner/updateBannerById')
    nextTick(() => {
        editBannerAlertRef.value.assignValueToInput(value.b_name, value.b_link)
    })
}

// 删除
// 批量删除
let isDeleteBatch = ref<boolean>(false)
const deleteBatch = () => {
    isDeleteBatch.value = !isDeleteBatch
}
let deleteDate = ref<any>([])
let isdeleteAlert = ref<boolean>(false)
let deleteIndex = ref<number>(-1) // 当前删除的轮播图的索引
const deleteRow = (index: number, value: any) => {
    isdeleteAlert.value = true
    deleteIndex.value = index
    deleteDate.value = [value]
}
// 获取选中需要删除的数据
let tableRef = ref<any>(null)
const getDeleteData = () => {
    deleteDate.value = tableRef.value.getSelectionRows()
    if(deleteDate.value.length < 1) {
        ElMessage({
            showClose: true,
            message: '请先选择需要删除的数据！',
            type: 'warning',
        })
        return
    }
    isdeleteAlert.value = true
}
// 点击批量输出的checkbox
const isShowDeleteSelection = () => {
    if(!isdeleteAlert.value) tableRef.value.clearSelection()
}

// 询问用户是否删除弹窗
// 弹窗数据
const deleteAlertData = computed(() => {
    return {
        title: '删除轮播图',
        message: '',
        confirmTitle: '删除',
        isShowCancleBtn: true,
        cancleTitle: '取消',
        isShowClose: true,
        size: 'large'
    }
})
// 取消删除
const onConcel = () => {
    isdeleteAlert.value = false
} 
// 确认删除
const onConfirm = () => {
    let bidString = ''
    deleteDate.value.forEach((item: any, index: any) => {
        if(index == (deleteDate.value.length - 1)) {
            bidString += `${ item.bid }`
        } else {
            bidString += `${ item.bid },`
        }
    })
    const data = {
        bid: bidString
    }
    manageBannerSe.getDeleteBannerById(data).then((res: any) => {
        if(res.status == 'success') {
            tableData.value.splice(deleteIndex.value, 1)
            isdeleteAlert.value = false
            getBannerList()
            ElMessage({
                showClose: true,
                message: '删除成功！',
                type: 'success',
            })
        } else {
            ElMessage.error('删除失败！')
        }
    })
} 

// 是否启用该轮播图
const changeBannerState = (bid: string, value: object) => {
    stateList.value[`${ bid }`].loading = !value.loading
    const data = {
        bid: bid,
        b_state: stateList.value[`${ bid }`].state ? 1 : 0
    }
    manageBannerSe.getUpadtaBannerById(data).then((res: any) => {
        if(res.status == 'success') {
            stateList.value[`${ bid }`].loading = !value.loading
        }
    })
}

onMounted(() => {
    getBannerList()
})
</script>
  
<style lang="less" scoped>
.banner-list {
    margin-top: 1rem;
    border-radius: 0.5rem;
    padding: 1rem 0;
    padding-top: 0rem !important;
    flex: 1;
    background-color: var( --pc-bg-white);
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: stretch;
    max-height: (100vh - 28rem);
    // :deep(.el-table) {
    //     border-radius: 0.5rem;
    //     flex: 1;
    //     height: fit-content !important;
    //     max-height: unset !important;
    //     .el-table__inner-wrapper {
    //         max-height: fit-content !important;
    //     }
    //     th, td {
    //         border-right: var(--el-table-border) !important;
    //         padding: 1rem 0.5rem;
    //     }
    //     td > div {
    //         overflow: hidden;

    //     }
    //     th, .el-table_1_column_1 {
    //         text-align: center;
    //     }
    // }
    // .demo-pagination-block + .demo-pagination-block {
    //     margin-top: 10px;
    // }
    // .demo-pagination-block .demonstration {
    //     margin-bottom: 16px;
    // }
    // .table-footer {
    //     padding-top: 0.6rem;
    //     box-sizing: border-box;
    //     max-height: 2rem;
    //     :deep(.el-pagination) {
    //         justify-content: flex-end;
    //     }
    // }

    .cell {
        line-height: 1.5;
        width: 100%;
        // height: 100%;
        height: 7rem;
        -webkit-line-clamp: 5;
        .img-preview {
            display: flex;
            align-items: center;
            width: 100%;
            height: 100%;
            justify-content: center;
            div {
                width: 90%;
                img {
                    width: 100%;
                }
            }
        }
    }
    :deep(.delete-btn) {
        span {
            color: var(--pc-font-white);
        }
    }
    
}
:deep(.el-table.delete-table) {
    .el-table__body-wrapper {
        max-height: 30rem !important;
    }
}
</style>